package com.zbw.weightlibrary.WeightSub;

import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import com.zbw.weightlibrary.Connector.BaseControlImpl;
import com.zbw.weightlibrary.Connector.IinfoCallback;
import com.zbw.weightlibrary.Connector.WeightData;
import com.zbw.weightlibrary.Util.ThreadPoolManager;
import java.io.IOException;
import java.util.UUID;

/**
 * 作者 ：Wesley
 * 时间 ：2019-12-26 11:29
 * 这个类是干嘛的？：WeightBluetooth
 * 蓝牙电子秤
 */
public class WeightBluetooth extends BaseControlImpl {
    private final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//android 蓝牙默认的套接字认证秘钥
    private final IinfoCallback mCallback;
    private final String address;
    private BluetoothSocket socket;


    public WeightBluetooth(Context context, IinfoCallback callback, WeightData data) {
        super(callback);
        mCallback = callback;
        address = data.getAddress();
    }


    @Override
    public void bleConnect() {
        if(address==null||"".equals(address)){
            mCallback.onConnect("请先选择需连接的蓝牙",false);
        }else{
            Connect(address);
        }
    }

    @Override
    public void bleDisconnect() {
        ReadWeight = false;
        mRecvData = null;
        try {
            if(socket!=null) {
                socket.close();
                socket = null;
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    public void getWeight() {
        try {
            ReadWeight(socket.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void stopWeight() {
        ReadWeight = false;
    }

    @Override
    public void clearTare() {

    }

    @Override
    public void tare() {

    }

    @Override
    public void zero() {

    }

    /**
     * 蓝牙连接
     * @param address 连接的机器ID
     */
    private void Connect(final String address){
        //Log.i("address",address);
        ThreadPoolManager.getInstance().executeTask(new Runnable() {
            @Override
            public void run() {
                //连接之前，先调一下断开
                try {
                    bleDisconnect();
                    Thread.sleep(500);
                }catch (Exception e){
                    e.printStackTrace();
                }
                //获取蓝牙连接适配器
                BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
                //由于蓝牙适配器搜索一个重量级的方法，如果存在连接目标ID，那就关闭蓝牙适配器的搜索方法，减少系统压力
                if (adapter.isDiscovering()) {
                    adapter.cancelDiscovery();
                }
                //通过设备id,获取设备对象
                BluetoothDevice device = BluetoothAdapter.getDefaultAdapter().getRemoteDevice(address);
                //Log.i("WeightBluetooth_device",device.getName());

                //先用默认的方式连接
                boolean is = false;
                try {
                    socket = device.createRfcommSocketToServiceRecord(uuid);
                    if (!socket.isConnected()) {
                        socket.connect();
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    is = true;
                }
                //如果正常连接出错，就用反射机制去连接
                if(is){
                    try {
                        socket = (BluetoothSocket) device.getClass().getMethod("createRfcommSocket", new Class[]{int.class}).invoke(device, 1);
                        socket.connect();
                        is = false;
                    }catch (Exception e){
                        e.printStackTrace();
                        mCallback.onConnect("连接失败",false);
                    }
                }
                if(!is){
                    mCallback.onConnect("连接成功！",true);
                }else {
                    try {
                        if(socket!=null) {
                            socket.close();
                            socket = null;
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }


}
